<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/21
 * Time: 9:24
 */

namespace app\admin\Decorate;

use app\admin\Imp\ImpDecorate;
use think\Cache;
use think\Request;
use think\Exception;

/**
 * Class CheckTimeDecorate
 * @package app\admin\Decorate
 */
class CheckTimeDecorate implements ImpDecorate
{
    /**
     * 该方法记录请求的频率并且判断是否请求频率过高
     */
    public function beforeDecorate()
    {
        //上一次请求的时间
        $time           =   Cache::get('lqc_request_time');
        if(empty($time)){return ;}
        $request_time   =   Request::instance()->server('REQUEST_TIME');
        if($request_time<=$time){ throw new Exception('抱歉请求频率过高！');}
    }


    /**
     *存入当前的请求结束时间
     */
    public function endDecorate()
    {
        //储存当前请求结束的时间
        $request_time           =       Request::instance()->server('REQUEST_TIME');
        $now_date               =       date('Y-m-d H:i:s',$request_time);
        //间隔多少秒可以访问接口
        $request_time_interval  =       (int) config('request_time_interval');
        //设置当前的请求接口的频率
        $date                   =       strtotime(date('Y-m-d H:i:s',strtotime("+ {$request_time_interval} second ".$now_date)));
        Cache::set('lqc_request_time',$date);
    }
}